﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.Runtime.InteropServices;
//new
using Bandit.UI;
using Bandit.UI.Controls;
using Bandit.Helpers;
using System.Diagnostics;
using System.Windows.Interop;

namespace MartiniDisplayAOI
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : BanditWindow
    {
        /// <summary>
        /// 视图模型
        /// </summary>
        public ViewModels.MainViewModel ViewModel { get { return App.MainViewModel; } }

        private IntPtr _CommunicationHandle = IntPtr.Zero;

        public MainWindow()
        {
            InitializeComponent();

            #region Window Loaded

            this.Loaded += delegate
            {
                ViewModel.OnClick = new Bandit.UI.MVVM.CommandHandler(OnClick);

                this.DataContext = ViewModel;

                this.txtProcessName.Text = "ETC.AOIInteractionTest";//this.Title = Process.GetCurrentProcess().ProcessName;

                System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
                dispatcherTimer.Tick += dispatcherTimer_Tick;
                dispatcherTimer.Interval = new TimeSpan(0, 0, 10);
                dispatcherTimer.Start();

                //ConnectProcessHandle();
            };

            this.btnConnect.Click += delegate
            {
                ConnectProcessHandle();
            };

            this.btnSend.Click += delegate
            {

                string data = txtMsg.Text;

                this.SendMessage(this._CommunicationHandle, Win32API.UserMessage, 0, data);

            };

            this.btnClear.Click += delegate
            {

                this.txtReceiveMsg.Clear();

            };

            #endregion


            


        }

        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            // code goes here
            ConnectProcessHandle();
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
            if(hwndSource != null)
            {
                hwndSource.AddHook(new HwndSourceHook(this.WndProc));
            }
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam,ref bool handled)
        {
            switch (msg)
            {
                case Win32API.UserMessage:
                    ReceiveMsg((int)lParam);
                    break;
                default:break;
            }
            return IntPtr.Zero;
        }

        List<byte> _BufferData = new List<byte>();
        private void ReceiveMsg(int lParam)
        {
            if (lParam != -1)
            {
                _BufferData.Add((byte)lParam);
            }
            else
            {
                byte[] buffer = _BufferData.ToArray();
                _BufferData.Clear();
                this.txtReceiveMsg.Text += Encoding.UTF8.GetString(buffer, 0, buffer.Length) + Environment.NewLine;
                this.txtReceiveMsg.ScrollToEnd();

                this.SendMessage(this._CommunicationHandle, Win32API.UserMessage, 0, "22_Pass");

            }

        }
        private void ConnectProcessHandle()
        {
            
            //var processArray = Process.GetProcessesByName(txtProcessName.Text);
            var processArray = Process.GetProcessesByName("ETC.AOIInteractionTest");
            if (processArray != null && processArray.Length > 0)
            {
                _CommunicationHandle = processArray[0].MainWindowHandle;

                connectStatus.Text = "Connect Success!";
                connectStatus.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF316C3E"));

            }
            else
            {
                connectStatus.Text = "No Connect!";
                connectStatus.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF7A2B2B"));

            }

        }

        private void SendMessage(IntPtr hWnd, int Msg,int wParam, string lParam)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(lParam);

            for(int i = 0; i < buffer.Length; i++)
            {
                Win32API.PostMessage(hWnd, Msg, wParam, buffer[i]);
            }

            Win32API.PostMessage(hWnd, Msg, wParam, -1);
        }

        #region OnClick Event

        private void OnClick(object parameter)
        {
            if (parameter != null)
            {
                switch (parameter.ToString())
                {
                    case "Setting":
                        {
                            ShowWindow<Windows.FrmSetting>(this);
                        }
                        break;
                    case "CheckUpdate":
                        if (!App.CheckUpdate())
                        {
                            this.ShowDialog(App.GetString("NotNeedUpdatePrompt"), App.GetString("Prompt"), MessageBoxButton.OK, Bandit.UI.DialogIcon.OK);
                        }
                        break;
                    case "About":
                        {
                            Windows.FrmAbout.Show(this);
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        #endregion
    }

    public class Win32API
    {
        public const int USER = 0x0400;
        public const int UserMessage = USER + 100;

        [DllImport("user32.dll")]
        public static extern void PostMessage(IntPtr hWnd, int msg, int wParam, int lParam);

        /// <summary>
        /// 查找窗体句柄
        /// </summary>
        /// <param name="className">类名</param>
        /// <param name="windowName">标题名</param>
        /// <returns></returns>
        [DllImport("user32.dll",CharSet = CharSet.Auto)]
        public static extern IntPtr FindWindow(string className,string windowName);

    }
}
